import * as fs from 'fs'
import { promisify } from 'util'

export default class Filesystem
{
    /**
     * Determine if a file exists.
     *
     * @param  {string}  path
     * @returns {Promise<boolean>}
     */
    public exists(path: string)
    {
        return promisify(fs.exists)(path);
    }

    /**
     * Get the contents of a file.
     *
     * @param  string  path
     * @return string
     *
     * @throws {Error}
     */
    public get(path: string)
    {
        if (this.isFile(path)) {
            return promisify(fs.readFile)(path).then(buf => buf.toString());
        }

        throw new Error("File does not exist at path {path}");
    }

    /**
     * Write the contents of a file.
     *
     * @param  {string}  path
     * @param  {string}  contents
     */
    public put(path: string, contents: string)
    {
        return promisify(fs.writeFile)(path, contents);
    }

    /**
     * Get the file's last modification time.
     *
     * @param  {string}  path
     */
    public lastModified(path: string)
    {
        return promisify(fs.stat)(path).then(stat => stat.mtime)
    }

    /**
     * Determine if the given path is a file.
     *
     * @param  string  file
     */
    public isFile(file: string)
    {
        return promisify(fs.stat)(file).then(stat => stat.isFile());
    }
}